﻿using Ebusiness_Framework.ConfigCenter;
using Ebusiness_Gateway.Data;
using Ocelot.Middleware;
using Polly;
using Serilog;
using Serilog.Events;
using SkyApm.AspNetCore.Diagnostics;
using Volo.Abp.Data;
using Ebusiness_Framework.SkyAPMConfig;
using Ebusiness_Framework.ConfigLoad;
using Microsoft.AspNetCore.Builder;

namespace Ebusiness_Gateway;

public class Program
{
    public async static Task<int> Main(string[] args)
    {
        var loggerConfiguration = new LoggerConfiguration()
#if DEBUG
            .MinimumLevel.Debug()
#else
            .MinimumLevel.Information()
#endif
            .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
            .Enrich.FromLogContext()
            .WriteTo.Async(c => c.File("Logs/logs.txt"))
            .WriteTo.Async(c => c.Console());

        //if (IsMigrateDatabase(args))
        //{
        //    loggerConfiguration.MinimumLevel.Override("Volo.Abp", LogEventLevel.Warning);
        //    loggerConfiguration.MinimumLevel.Override("Microsoft", LogEventLevel.Warning);
        //}

        Log.Logger = loggerConfiguration.CreateLogger();

        try
        {
            var builder = WebApplication.CreateBuilder(args);
            builder.Host.AddAppSettingsSecretsJson()
                .UseAutofac()
                .UseSerilog();

            #region 加载配置
            {
                builder.UseConfigLoad();
            }
            #endregion

            #region  配置中心配置  加载nacos配置
            {
                //builder.UseConfigCenter();
            }
            #endregion


            #region 配置链路监控
            {
                //配置链路监控
                //builder.Services.UseSkyAPM();
            }
            #endregion

            #region  //网关配置 ocelot
            {
                // 加载 ocelot.json
                var conf = builder.Configuration["ASPNETCORE_ENVIRONMENT"];
                if (conf == "Development")
                    builder.Configuration.AddJsonFile("ocelot.json", optional: false, reloadOnChange: true);
                else
                    builder.Configuration.AddJsonFile($"ocelot.{conf}.json", optional: false, reloadOnChange: true);
            }
            #endregion

            await builder.AddApplicationAsync<Ebusiness_GatewayModule>();

            var app = builder.Build();

            #region api网关 ocelot
            {
                app.UseWebSockets(); // ⚡ 必须启用 WebSocket
                // 🧠 中间件分支：处理 /api/abp 路由 → 交给 Ocelot
                app.MapWhen(
                    context => context.Request.Path.StartsWithSegments("/User", StringComparison.OrdinalIgnoreCase)
                    || context.Request.Path.StartsWithSegments("/Product", StringComparison.OrdinalIgnoreCase)
                    || context.Request.Path.StartsWithSegments("/Order", StringComparison.OrdinalIgnoreCase)
                    || context.Request.Path.StartsWithSegments("/api/app/order", StringComparison.OrdinalIgnoreCase)
                    || context.Request.Path.StartsWithSegments("/maphub", StringComparison.OrdinalIgnoreCase),
                    abpAbpBranch =>
                    {
                        //abpAbpBranch.UseRouting();
                        abpAbpBranch.UseOcelot().Wait(); // 同步等待 Ocelot 初始化完成
                    });
            }
            #endregion

            await app.InitializeApplicationAsync();
            Log.Information("Starting Ebusiness_Gateway.");
            await app.RunAsync();
            return 0;
        }
        catch (Exception ex)
        {
            if (ex is HostAbortedException)
            {
                throw;
            }

            Log.Fatal(ex, "Ebusiness_Gateway terminated unexpectedly!");
            return 1;
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }

    private static bool IsMigrateDatabase(string[] args)
    {
        return args.Any(x => x.Contains("--migrate-database", StringComparison.OrdinalIgnoreCase));
    }
}
